/**
 * create by young (young2f@outlook.com) on 2020/10/30
 */


'use strict';
import styles from '../../User/Register.less';
import {Button, Checkbox, Form, Input, notification, Popover, Progress, Select, Switch} from 'antd';

import React from 'react';
import moment from 'moment';
import {EyeInvisibleOutline, EyeTwoTone} from '@ant-design/icons';
import ComponentBase from '../../../components/Base/ComponentBase';
import notify from '../../../components/NotificationExtra';

const {Option} = Select;
const FormItem = Form.Item;
moment.locale('zh-cn');
const passwordStatusMap = {
  ok: <div className={styles.success}>强度：强</div>,
  pass: <div className={styles.warning}>强度：中</div>,
  poor: <div className={styles.error}>强度：太短</div>,
};

const passwordProgressMap = {
  ok: 'success',
  pass: 'normal',
  poor: 'exception',
};
@Form.create()
export default class ModalEditUser extends ComponentBase {
  constructor(props) {
    super(props);
    this.state = {
      confirmDirty: false,
      visible: false,
      help: '',
      prefix: '86',
    };
  }

  componentDidMount() {
    this.props.dispatch({type: 'role/findRoles', payload: {}})
      .then(res => {
        const {result} = res;
        this.setState({role: result});
      });
  }

  componentWillUnmount() {

  }

  getPasswordStatus = () => {
    const {form} = this.props;
    const value = form.getFieldValue('password');
    if (value && value.length > 9) {
      return 'ok';
    }
    if (value && value.length > 5) {
      return 'pass';
    }
    return 'poor';
  };

  handleConfirmBlur = e => {
    const {value} = e.target;
    const {confirmDirty} = this.state;
    this.setState({confirmDirty: confirmDirty || !!value});
  };

  checkConfirm = (rule, value, callback) => {
    const {form} = this.props;
    if (value && value !== form.getFieldValue('password')) {
      callback('两次输入的密码不匹配!');
    } else {
      callback();
    }
  };

  checkPassword = (rule, value, callback) => {
    if (!value) {
      this.setState({
        help: '请输入密码！',
        visible: !!value,
      });
      callback('error');
    } else {
      this.setState({
        help: '',
      });
      const {visible, confirmDirty} = this.state;
      if (!visible) {
        this.setState({
          visible: !!value,
        });
      }
      if (value.length < 6) {
        callback('error');
      } else {
        const {form} = this.props;
        if (value && confirmDirty) {
          form.validateFields(['confirm'], {force: true});
        }
        callback();
      }
    }
  };

  changePrefix = value => {
    this.setState({
      prefix: value,
    });
  };

  renderPasswordProgress = () => {
    const {form} = this.props;
    const value = form.getFieldValue('password');
    const passwordStatus = this.getPasswordStatus();
    return value && value.length ? (
      <div className={styles[`progress-${passwordStatus}`]}>
        <Progress
          status={passwordProgressMap[passwordStatus]}
          className={styles.progress}
          strokeWidth={6}
          percent={value.length * 10 > 100 ? 100 : value.length * 10}
          showInfo={false}
        />
      </div>
    ) : null;
  };

  submit = () => {
    const {modalRef, dispatch, form, user, editPassword} = this.props;
    form.validateFields((err, values) => {
      if (err) {
        const {code} = err;
        const {errors} = code;
        errors.forEach(item => {
          notification.error(item);
        });
        return;
      }
      this.process(values);
    });
  };

  async process(values) {
    const {modalRef, dispatch, editPassword} = this.props;
    const {password, oldPassword} = values;

    values.password = editPassword ? this.getCryptoPassword(password) : undefined;
    values.oldPassword = editPassword ? this.getCryptoPassword(oldPassword) : undefined;

    if (editPassword) {
      const res = await dispatch({
        type: 'user/updatePassword',
        payload: {
          ...values
        },
      });
      console.log('update pass',res)
      const {status, message,result} = res;
      if (status === 'ok') {
        notify({type: 'info', message: '操作成功，请重新登录！'});
        dispatch({
          type: 'user/logout',
        });
        modalRef.close();
        return;
      }
      notify({type: 'error', message});
      return;
    }


    const {role} = this.state;
    const _role = _.find(role, item => item.roleCode === values.roleCode);
    values.roleName = _role.roleName;
    this.props.result(values);
    modalRef.close();
  }

  getOption = () => {
    const {role} = this.state;
    if (!role) return null;
    const temp = [];
    role.map(item => {
      const {roleName, roleCode} = item;
      temp.push(
        <Option value={roleCode}>{roleName}</Option>,
      );
    });
    return temp;
  };

  render() {
    const {form, user = {}, update, editPassword} = this.props;
    const {username, nickname, password, roleCode} = user;
    const {getFieldDecorator} = form;
    const {help, visible} = this.state;
    const {isAdmin} = user;
    let str = update ? '更新' : '注册';
    return (
      <div className={styles.main}>
        <Form>
          <FormItem>
            {getFieldDecorator('username', {
              initialValue: username,
              rules: [
                {required: true, message: '请输入用户名！'},
              ],
            })(<Input disabled={username} size="large" placeholder="用户名"/>)}
          </FormItem>
          <FormItem>
            {getFieldDecorator('nickname', {
              initialValue: nickname,
              rules: [
                {required: true, message: '请输入员工姓名！'},
              ],
            })(<Input disabled={editPassword} size="large" placeholder="员工姓名"/>)}
          </FormItem>
          {editPassword && <FormItem help={help}>
            {getFieldDecorator('oldPassword', {
              rules: [
                {
                  required: true,
                  message: '请输入原密码！',
                }]
            })(<Input.Password size="large"
                               iconRender={visible => (visible ? <EyeTwoTone/> : <EyeInvisibleOutline/>)}
                               placeholder="请输入原密码"/>)}

          </FormItem>}
          {editPassword && <FormItem help={help}>
            <Popover
              content={
                <div style={{padding: '4px 0'}}>
                  {passwordStatusMap[this.getPasswordStatus()]}
                  {this.renderPasswordProgress()}
                  <div style={{marginTop: 10}}>
                    请至少输入 6 个字符。请不要使用容易被猜到的密码。
                  </div>
                </div>
              }
              overlayStyle={{width: 240}}
              placement="right"
              visible={visible}
            >
              {getFieldDecorator('password', {
                initialValue: password,
                rules: [{validator: this.checkPassword}],
              })(<Input.Password size="large"
                                 iconRender={visible => (visible ? <EyeTwoTone/> : <EyeInvisibleOutline/>)}
                                 placeholder="至少6位密码，区分大小写"/>)}
            </Popover>
          </FormItem>}
          {editPassword && !password && <FormItem>
            {getFieldDecorator('cpassword', {
              rules: [
                {
                  required: true,
                  message: '请确认密码！',
                },
                {
                  validator: this.checkConfirm,
                },
              ],
            })(<Input.Password size="large" iconRender={visible => (visible ? <EyeTwoTone/> : <EyeInvisibleOutline/>)}
                               type="password" placeholder="确认密码"/>)}
          </FormItem>}
          <FormItem>
            {getFieldDecorator('roleCode', {
              initialValue: roleCode,
              rules: [
                {
                  required: true,
                  message: '请选择角色！',
                },
              ],
            })(
              <Select
                style={{width: '90%'}}
                allowClear={true}
                size="large"
                placeholder="用户角色"
                disabled={isAdmin || editPassword}
              >
                {this.getOption()}
              </Select>,
            )}
          </FormItem>
          <FormItem>
            {getFieldDecorator('isAdmin', {
              initialValue: isAdmin,
            })(
              <Switch
                defaultChecked={isAdmin}
                allowClear={true}
                size="large"
                title="是否管理员"
                checkedChildren="管理员" unCheckedChildren="非管理员"
              >
              </Switch>,
            )}
          </FormItem>
          <FormItem>
            <Button
              size="large"
              // loading={submitting}
              className={styles.submit}
              type="primary"
              // htmlType="submit"
              onClick={this.submit.bind(this)}
            >
              {str}
            </Button>
          </FormItem>
        </Form>
      </div>
    );
  }
}
